<template>
  <view class="uni-container compay-business-licence">

    <uni-popup ref="message" type="message">
				<uni-popup-message type="error" :message="messageText" :duration="1500"></uni-popup-message>
		</uni-popup>

    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="company_license_icon" label="营业执照" required>
        <uni-file-picker ref="files" @select="(e)=>fileList=e" @delete="()=>fileList==null" :auto-upload="false" file-mediatype="image" file-extname="jpg,png" :limit="1" return-type="array" v-model="formData.company_license_icon"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="company_license_credit_code" label="统一社会信用代码" required>
        <uni-easyinput type="text" placeholder="请填写统一社会信用代码" v-model="formData.company_license_credit_code" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="company_holder_name" label="法定代表人/经营者" required>
        <uni-easyinput type="text" placeholder="请填写公司法定代表人/经营者" v-model="formData.company_holder_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="company_name" label="名称" required>
        <uni-easyinput type="text" placeholder="请填写公司名称" v-model="formData.company_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="company_location" label="经营场所/住所" required>
        <uni-easyinput type="textarea" :maxlength="500" placeholder="请填写公司经营场所/住所" v-model="formData.company_location" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="company_register_capital" label="注册资本">
        <uni-easyinput type="string" :maxlength="11" placeholder="请填写公司注册资本(选填)" v-model="formData.company_register_capital" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="company_register_date" label="注册/成立日期" required>
        <uni-datetime-picker type="date" return-type="timestamp" v-model="formData.company_register_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="company_issuer" label="发证/登记机关" required>
        <uni-easyinput type="text" placeholder="请填写公司发证/登记机关" v-model="formData.company_issuer" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="company_license_valid_date" label="营业执照有效期" required>
        <uni-data-checkbox  mode="button"  v-model="licenseSelect" :localdata="licenseValidSelect"></uni-data-checkbox>
        <uni-datetime-picker v-if="licenseSelect!==0" type="date" return-type="timestamp" v-model="licenseSelectTime"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="company_approval_date" label="核准日期" required>
        <uni-datetime-picker type="date" return-type="timestamp" v-model="formData.company_approval_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="company_business_scope" label="经营范围" required>
        <uni-easyinput type="textarea" :maxlength="500" placeholder="请填写公司经营范围" v-model="formData.company_business_scope" trim="both"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <lay-button type="normal" @click="submit">确认提交</lay-button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <lay-button @click="closeAll">取消关闭</lay-button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/compay-business-licence.js';
  import {store} from '@/uni_modules/uni-id-pages/common/store.js'

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'compay-business-licence';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "merchant_id": store.userInfo.merchant_id,
        "company_license_icon": [],
        "company_license_credit_code": "",
        "company_holder_name": "",
        "company_name": "",
        "company_location": "",
        "company_register_capital": "",
        "company_register_date": null,
        "company_issuer": "",
        "company_license_valid_date": "",
        "company_approval_date": null,
        "company_business_scope": ""
      }
      return {
        formData,
        formOptions: {},
        fileList:null,
        messageText:``,
        licenseSelect:0,
        licenseSelectTime:``,
        licenseValidSelect:[{
          text: '长期',
					value: 0
        },{
          text: '其他',
					value: 1
        }],
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    watch:{
      licenseSelect:{
        handler:function(val){
          if(val==0){
            this.formData.company_license_valid_date=`长期`
          }else{
            this.formData.company_license_valid_date=this.licenseSelectTime+``
          }
        },
        immediate:true
      },
      licenseSelectTime:{
        handler:function(val){
          this.formData.company_license_valid_date=val+``;
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then(async (res) => {

          if(this.fileList==null){
            this.messageText=`营业执照必须上传`;
            return this.$refs.message.open()
          }

          res.company_license_icon= await this.$refs.files.upload();

          if(res.company_register_capital.trim()!==``){
            if(isNaN(res.company_register_capital)){
                this.messageText=`注册资本填写有错误`;
                return this.$refs.message.open()
              }else{
                res.company_register_capital=res.company_register_capital
            }
          }
          res.merchant_id= store.userInfo.merchant_id
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
